require 'drb'
require 'config_reader'
require 'agent_interface'
require 'socket'
require 'singleton'

class Agent
  include Singleton
  
  attr_reader :host, :port, :server, :interface
  def initialize()
    reader = ConfigReader.new('agent_config.yml')
    @host = Socket.gethostname
    @port = reader.port
    @server = reader.server
    @interface = AgentInterface.new(self, reader.shared_files)
  end

  def register_with_server
    #TODO can this cause race condition?
    server_interface.register(@host, @port)
  end

  def server_interface
    DRbObject.new(nil, @server)
  end

  def start
    DRb.start_service("druby://#{@host}:#{@port}", @interface)
    register_with_server
    @interface.publish_to_server
  end
  
  def daemon
    DRb.thread.join
  end

  def stop
    DRb.stop_service
  end
end
